package jp.co.ysl.test;

import java.lang.reflect.Proxy;
import java.util.Iterator;
import java.util.List;

public class ServiceProxyFactory {

	/**
	 *
	 */
	private static final long serialVersionUID = -1261622934781826494L;

	public static Object createProxyClass(String classId) throws Exception {

		ClassInfo classInfo = new ClassInfo();

		Object targetObject = null;

		try {
			classInfo = ClassInfoUtil.getInstance().getClassInfo(classId);
		} catch (Exception e){
			targetObject = Class.forName(classId).newInstance();
		}

		List handlers = classInfo.getHandler();

		if (classInfo.getHandler().size() == 0) {
			handlers.add("jp.co.ysl.test.DefaultInvocationHandler");
		}

		Object handlerTargetObject = targetObject;
		Object proxy = null;
		for (Iterator it = handlers.iterator(); it.hasNext();) {
			String handlerType = (String) it.next();
			DefaultInvocationHandler handler = (DefaultInvocationHandler) Class
					.forName(handlerType).newInstance();
			handler.setTargetObject(handlerTargetObject);

			proxy = Proxy.newProxyInstance(targetObject.getClass()
					.getClassLoader(), targetObject.getClass().getInterfaces(),
					handler);

			handlerTargetObject = proxy;
		}

		return proxy;
	}

}
